$j(document).ready(function () {
	//验证
	
});

$j.fn.extend({
	loading2:function(){
		return this.each(function(){
			$j(this).html('<td colspan="11"><div class="loading_box"><div class="progress_bar"><img src="'+__ctxPath+'/images/icon/loadingBig.gif"/>loading...</div></div></td>');			
		});
	},
	loading3:function(){
		return this.each(function(){
			$j(this).html('<td colspan="11"><div class="loading_box"><div class="progress_bar"><img src="'+__ctxPath+'/images/icon/loadingBig.gif"/>'+__FMT.salesOrder_processing+'</div></div></td>');			
		});
	},
	loading4:function(){
		return this.each(function(){
			$j(this).html('<div class="loading_box"><div class="progress_bar"><img src="'+__ctxPath+'/images/icon/loadingBig.gif"/>'+__FMT.salesOrder_addOrdering+'</div></div>');			
		});
	}
	
});


//客户选择器选择客户后的回调
function selectCustomerCallback(customer){
	closeDialogOfcustomerSelector();
	$j('#customerId').val(customer.customerId);
	$j('#useAnonymous').attr("checked",false);//使用匿名不选
	//加载客户详细信息
	$j('#customerDetail').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=loadCustomerDetail4AddPanel&customerId='+customer.customerId);
	
	//重新加载收货人和支付配送方式
	loadConsigneeAndPayShipMethodDiv4AddPanel(true);
	
}

//加载送货地址和配送、支付方式
function loadConsigneeAndPayShipMethodDiv4AddPanel(loadAddressFlag){
	var jPanel = $j('#salesOrderForm');
	if(jPanel.find('#consigneeAndPayShipMethodDiv').length != 0){
		var params = jPanel.find(':input').serializeArray();
		if(loadAddressFlag != null && loadAddressFlag != undefined){
			//要重新加载地址
			params.push({"name":"loadAddressFlag","value":"true"});
		}
		$j('#orderDetail').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=loadOrderInfo4AddPanel',params);
		
	}
}

//是否使用匿名
function toggleUseAnonymous(checkbox){
	if(checkbox.checked){
		$j('#customerId').val("");
		$j('#customerDetail').empty();
	}
	
}

//货品选择器选择货品后的回调
function addProductSkuCallback(productSkuArray){
	if(productSkuArray.length != 0){
		$j("#addHint").hide();
	}
	for (var i = 0; i < productSkuArray.length; i++) {
		var productSku = productSkuArray[i];
		var jProductSkuExist = $j('#productSkuTable').find('input[name="productSkuCodes"][value="'+productSku.productSkuCode+'"]');
		if (jProductSkuExist.length != 0) {
			//已存在
			try {
				var jQuantity = jProductSkuExist.parent('td').find('input[name="skuQuantities"]');
				var quantity=new Number(jQuantity.val());
				jQuantity.val(quantity+1);
			}catch(err){
				
			}
		}else{	
			//不存在
			var html='<tr class="order_item">';
			var mediaUrl = productSku.imageUrl=="" ? productSku.productImageUrl : productSku.imageUrl;
			var src_s0 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s0"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
			html += '<td><img src="'+src_s0+'" width="58" height="58" onerror="this.src=__defaultImage_s0;this.onerror=\'\'" /></img></td>';
			html += '<td>'+productSku.productSkuCode+'</td>';
			html += '<td>'+productSku.productName+'&nbsp;&nbsp;&nbsp;'+productSku.orderSkuDisplayOption+'</td>';
			html += '<td><input type="text" validconf="required,integer" name="skuQuantities" class="form-input"  style="width:80px;" id="skuQuantity'+productSku.productSkuId+'" value="' + productSku.minOrderQuantity + '"/>';
			html += '<input type="hidden" name="productSkuCodes" value="'+productSku.productSkuCode+'" />';
			html += '</td>';
			html += '<td align="center"><a href="javascript:void(0)" class="del" onclick="delOrderSku(this)">&nbsp;</a></td>';
			html += '</tr>';
			$j('#productSkuTable').append(html);
			applyValidate($('skuQuantity'+productSku.productSkuId),"required,integer");
		}	
	}
	closeDialogOfproductSkuSelector(); 
	//重新加载收货人和支付配送方式
	loadConsigneeAndPayShipMethodDiv4AddPanel();
	
}

//删除货品
function delOrderSku(orderSkuDOM){
	$j(orderSkuDOM).parents('tr:first').remove();
	if ($j('#productSkuTable').find('input[name="productSkuCodes"]').length == 0) {
		$j("#addHint").show();
	}
	
	//重新加载收货人和支付配送方式
	loadConsigneeAndPayShipMethodDiv4AddPanel();
	
}

//下一步显示订单信息
function showOrderInfo(btnDOM){
	//判断条件
	
	if($j('#customerId').val()== "" && !$j('#useAnonymous').get(0).checked){
		//检查是否有选择客户或使用匿名
		alert(__FMT.salesOrder_addPanel_tip_selectCustomerFirst);
		return;
	}
	if($j('#productSkuTable').find('input[name="productSkuCodes"]').length == 0){
		//检查是否有添加货品
		alert(__FMT.salesOrder_addPanel_tip_addProductFirst);
		return;
	}
	if(!validateForm($('customerAndProductDiv'))){
		alert(__vaMsg.notPass);
		return;
	}
	
	var jAddPanel = $j('#salesOrderForm');
	var params = jAddPanel.find(':input').serializeArray();
	$j('#orderDetail').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=loadOrderInfo4AddPanel',params);
	$j(btnDOM).remove();
}

//渲染地区修改区域
function renderPanelRegionModifyDiv(buttonDom){
	var regionId = $j('input[name="regionId"]').val();
	$j('#regionModifyDiv').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=renderPanelRegionModify&regionId='+regionId);
	$j('#regionShowDiv').empty();
}
//渲染地区显示区域
function renderPanelRegionShowDiv(buttonDom){
	if(validateForm($j('#regionModifyDiv').get(0))){
		var regionId = $j('input[name="regionId"]').val();
		$j('#regionShowDiv').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=renderPanelRegionShow&regionId='+regionId);
		$j('#regionModifyDiv').empty();
		
		//加载支付与配送方式
		var jAddPanel = $j('#salesOrderForm');
		var params = jAddPanel.find(':input').serializeArray();
		$j('#payShipMethodDiv').loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=loadPayShipMethodDiv4AddPanel&regionId='+regionId,params);
	}else{
		alert(__vaMsg.notPass);
	}
}

//更改支付方式 regionId必须从外部传入,因为送货地区与支付方式是同时load的
function changePaymentMethod(paymentMethodDOM,regionId){
	if(regionId == null || regionId == undefined){
		//地区为空则不需要改变配送方式和自提方式
		return;
	}
	
	var jSelectedPaymentMethodId = $j("input:radio[name='paymentMethodId']:checked");
	//是否货到付款
	var isCod = jSelectedPaymentMethodId.attr("isCod");
	//当前支付方式id
	var paymentMethodId = jSelectedPaymentMethodId.val();
	
	//----是否显示付款方式---	
	if (isCod == 1) {
		$j("[group*='cod']").show();
	} else {
		$j("[group*='cod']").hide();
	}
	
	if (paymentMethodId == 5) {
		//case:自提方式
		$j("[group*='shippingMethod']").hide();
		$j("[group*='selfCollect']").show();
		
		
		$j("#shippingMethodList").empty();
		//提货点
		$j("#selfCollectionCentreList").loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=loadSelfCollectionCentre4AddPanel&regionId='+regionId+'&paymentMethodId='+paymentMethodId);
	} else {
		//case:非自提方式
		$j("[group*='shippingMethod']").show();
		$j("[group*='selfCollect']").hide();
		
		$j("#selfCollectionCentreList").empty();
		//配送方式
		$j("#shippingMethodList").loading().load(__ctxPath+'/order/salesOrder/blank.html?doAction=loadShippingMethod4AddPanel&regionId='+regionId+'&paymentMethodId='+paymentMethodId);
		
	}
	
}

//更改配送方式
function changeShippingMethod(shippingMethodDOM){
	var jSelectedShippingRateId = $j("input:radio[name='shippingRateId']:checked");
	//是否支持指定配送时间
	var supportSpecifyingDeliveryTime = jSelectedShippingRateId.attr("supportSpecifyingDeliveryTime");
	if (supportSpecifyingDeliveryTime  == 1) {
		$j("[group*='specifiedDeliveryTime']").show();
	} else {
		$j("[group*='specifiedDeliveryTime']").hide();
	}
}

//改变是否支持发票
function toggleHasInvoice(checkboxDOM){
	if (checkboxDOM.checked) {
		$j("#hasInvoice").val("1");
		$j("#invoiceTitle").val("");
		applyValidate($j("#invoiceTitle").get(0),"required,maxlength=128");
		$j("#invoiceTitleDiv").show();
	} else {
		$j("#hasInvoice").val("0");
		$j("#invoiceTitle").val("");
		removeValidate($j("#invoiceTitle").get(0));
		$j("#invoiceTitleDiv").hide();
	}
}

//改变包装
function changeWrap(selectDOM){
	if(selectDOM.value != ""){
		$j("#wrapNote").val("");
		$j("#wrapNoteDiv").show();
	}else{
		$j("#wrapNote").val("");
		$j("#wrapNoteDiv").hide();
	}
}

//显示预览面板
function showPreviewPanel(){
	$j('#addPreviewPanel').parents('.ui-dialog:first').find('.ui-dialog-buttonpane').show(); //预览窗口按钮显示
	if(checkOrder()){
		var params = $j('#salesOrderForm :input').serializeArray();
		dlgaddPreviewPanel_show(params);
	}
}
//添加订单
function addOrder(){
	if (checkOrder()) {
		$j('#addPreviewPanel').parents('.ui-dialog:first').find('.ui-dialog-buttonpane').hide(); //预览窗口按钮隐藏
		$j('#addPreviewPanel #proccessing').loading4();
		var params = $j('#salesOrderForm :input').serializeArray();
		$j.post(__ctxPath+'/order/salesOrder/blank.html?doAction=addOrder',params,addOrderCallback,"json");
	}
}
//添加订单callback
function addOrderCallback(data){
	if(data.error){
		alert(data.error);
		dlgaddPreviewPanel_close();
		return;
	}
	window.location.href = __ctxPath+"/order/salesOrder.html?doAction=addOrderSuccess&orderNo="+data.orderNo;		
}
//检查下单资料
function checkOrder(){
	var jPanel = $j('#salesOrderForm');
	var isConsigneeVirtual = false;
	if(jPanel.find('#isConsigneeVirtual').length != 0){
		isConsigneeVirtual = true;
	}
	
	if($j('#customerId').val()== "" && !$j('#useAnonymous').get(0).checked){
		//检查是否有选择客户或使用匿名
		alert(__FMT.salesOrder_addPanel_tip_selectCustomerFirst);
		return false;
	}
	if($j('#productSkuTable').find('input[name="productSkuCodes"]').length == 0){
		//检查是否有添加货品
		alert(__FMT.salesOrder_addPanel_tip_addProductFirst);
		return;
	}
	
	if(!isConsigneeVirtual && jPanel.find('#regionShowDiv input[name="regionFullName"]').length != 0 && jPanel.find('#regionShowDiv input[name="regionFullName"]').val().trim() ==""){		
		//检查收货地区是否已填写
		alert(__FMT.salesOrder_panel_region_needModify);
		return false;
	}
	if(!isConsigneeVirtual && jPanel.find('#regionShowDiv input[name="regionId"]').length == 0){
		//检查收货地区是否已确定
		alert(__FMT.salesOrder_panel_region_needConfirm);
		return false;
	}
	
	
	if(!validateForm(jPanel.get(0))){
		alert(__vaMsg.notPass);
		return false;
	}
	return true;
}
